﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace StationUpdate.Util
{
    public class AuthUtil
    {
        /// <summary>
        /// 不带参数
        /// </summary>
        /// <returns></returns>
        public static string getAuth()
        {
            return makeAuth(SysData.appId, SysData.appKey);
        }
        /// <summary>
        /// 带参数
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string getAuth(string content)
        {
            return makeAuth(content,SysData.appId, SysData.appKey);
        }

        private static long getCurrentTimeMillis()
        {
            long currentTicks = DateTime.Now.Ticks;
            DateTime dtFrom = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            long currentMillis = (currentTicks - dtFrom.Ticks) / 10000;
            return currentMillis;
        }

        /**
	 * @param appId			appid
	 * @param appKey		appKey
	 * @return	返回不带参数的加密
	 */
        private static string makeAuth(string appId, string appKey)
        {
            long ctm = getCurrentTimeMillis();
            string data = "appid=" + appId + "&timestamp=" + ctm;
            string digest = genHmac(data, appKey);
            return "HmacSHA " + appId + ":" + ctm + ":" + digest;
        }

        /**
         * @param content		传输内容部分  :"K1=V1&K2=V2"
         * @param appId			appId
         * @param appKey		appKey
         * @return	返回带参数的加密
         */
        private static string makeAuth(string content, string appId, string appKey)
        {
            long ctm = getCurrentTimeMillis();
            string data = content + "&appid=" + appId + "&timestamp=" + ctm;
            string digest = genHmac(data, appKey);
            return "HmacSHA " + appId + ":" + ctm + ":" + digest;
        }
        
        private  static string genHmac(string data, string key)
        {
            HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(key));
            byte[] byteText = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(data));
            return System.Convert.ToBase64String(byteText);

        }
    }
}
